package cn.itcast.bos.web.action.system;

import java.io.IOException;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.UserService;
import cn.itcast.bos.web.action.common.BaseAction;

@Namespace("/")
@ParentPackage("struts-default")
@Scope("prototype")
@Controller
public class UserAction extends BaseAction<User> {
	private static final long serialVersionUID = 1L;
	@Autowired
	private UserService userService;
	
	//登录
	@Action(value = "user_login", results = { @Result(name = "success", location = "index.html", type = "redirect"),
			@Result(name = "login", location = "login.html", type = "redirect") })
	public String login() {
		// 基于shiro实现登录
		Subject subject = SecurityUtils.getSubject();
		// 用户名和密码信息
		AuthenticationToken usernamePasswordToken = new UsernamePasswordToken(model.getUsername(), model.getPassword());
		try {
			// 登录
			subject.login(usernamePasswordToken);
			// 登录成功
			return SUCCESS;
		} catch (AuthenticationException e) {
			e.printStackTrace();
			// 登录失败
			return LOGIN;
		}
	}
	//登出
	@Action(value = "user_logout", results = { @Result(name = "success", location = "index.html", type = "redirect") })
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		// 登出
		subject.logout();
		return SUCCESS;
	}
	//查询所有
	@Action("user_list")
	public void list() throws IOException{
		List<User> users = userService.findAll();
		String jsonString = JSONArray.toJSONString(users, SerializerFeature.DisableCircularReferenceDetect);
		ServletActionContext.getResponse().setContentType("application/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().write(jsonString);
	}
	//添加
	private String[] roleIds;
	
	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}
	@Action(value="user_save",results={@Result(name="success",location="./pages/system/userlist.html",type="redirect")})
	public String save(){
		userService.save(model,roleIds);
		return SUCCESS;
	}
}
